//
//  WBHomeListViewModel.swift
//  weibo
//
//  Created by yanghong on 15/12/11.
//  Copyright © 2015年 杨鸿. All rights reserved.
//

import UIKit

class WBHomeListViewModel: NSObject {
    
    //装有模型的数组
    var homeList: [WBStatuedViewModel]?
    
    //加载数据
    
    func loadData(isPullUp: Bool, complete: (isSuccessed: Bool, count: Int)->()) {
        
        var maxId = isPullUp == true ? (homeList?.last?.status?.id ?? 0) : 0
        
        if maxId > 0 {
         
            maxId -= 1
        }
        let sinceId = isPullUp == true ? 0 : (homeList?.first?.status?.id ?? 0)
        
        WBNetworkingTools.shareNetworking.loadHomeData(WBUserAccountViewModel.sharedAccount.accessToken!, maxid: maxId, sinceId: sinceId) { (response, error) -> () in
            //加载失败
            if error != nil {
            
             print("首页数据请求失败")
                complete(isSuccessed: false, count: 0 )
                return
            }
            //在这里数据就表示请求回来了
            guard let result = response as? [String: AnyObject] else {
             print("数据不是一个字典")
                return
            
            }
            // [[String: AnyObject]]
            guard let statusDict = result["statuses"] as? [[String: AnyObject]] else {
            
              print("statuses is not exsit")
             return
            }
            //实例化一个临时数据
            
            var tempArray = [WBStatuedViewModel]()
            
            //字典转模型
            
            for value in statusDict {
                let statues = WBStatues(dict: value)
                tempArray.append(WBStatuedViewModel(status: statues))
            }
            
            if self.homeList == nil {
            
              self.homeList = [WBStatuedViewModel]()
            
            }
            if isPullUp {
            
              self.homeList = self.homeList! + tempArray
            
            }else{
              
                self.homeList = tempArray + self.homeList!
            
            }
   
           complete(isSuccessed: true, count: tempArray.count)
        }

    }

}
